package com.joker;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;

import static com.joker.ZookeeperConstant.ZK_ADDRESS;

public class DistributedLockFactory {
    private static final ConcurrentHashMap<String, DistributedLock> lockCache = new ConcurrentHashMap<>();
    private static CuratorFramework client;

    static {
        client = CuratorFrameworkFactory.newClient(
                ZK_ADDRESS,
                new ExponentialBackoffRetry(1000, 3)
        );
        client.start();
    }

    public static DistributedLock getLock(String lockPath) {
        return lockCache.computeIfAbsent(lockPath, path ->
                new DistributedLock(client, path));
    }

    public static void close() {
        if (client != null) {
            client.close();
        }
    }
}

